package com.llc.spring.cloud.sdk.core.http;

import com.alibaba.fastjson.JSON;
import com.llc.spring.cloud.sdk.core.DefaultGatewaySelector;
import com.llc.spring.cloud.sdk.core.ex.RequestException;
import com.llc.spring.cloud.sdk.core.util.StringUtil;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * time 2018/8/27 9:26
 *
 * @author xiaojie.zhu <br>
 */
public abstract class AbstractHttpClient implements HttpClient{


    protected String baseUrl;
    protected String path;
    protected Map<String,Object> parameter;
    /**
     * true get
     * false post
     */
    protected boolean get = true;
    protected Object postBean;


    public AbstractHttpClient(String path, Map<String,Object> parameter, Object postBean,boolean get) {
        this.setPath(path);
        this.parameter = parameter;
        this.get = get;
        this.postBean = postBean;
    }


    @Override
    public String getResult() {
        this.setBaseUrl(DefaultGatewaySelector.getInstance().getGatewayUrl());
        String response = this.request();
        Result result = JSON.parseObject(response, Result.class);
        if(result.getCode() == 0){
            return JSON.toJSONString(result.getData());
        }else{
            throw new RequestException(result.getMsg() , result.getCode());
        }
    }


    protected abstract String request();




    protected String toParameter(){
        if(this.parameter instanceof Map){
            Map<String,Object> param = (Map<String, Object>) parameter;
            StringBuffer sb = new StringBuffer();
            if(param != null && param.size() > 0){
                Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Object> entry = iterator.next();
                    if(!StringUtil.isEmpty(entry.getKey()) && entry.getValue() != null){
                        try {
                            sb.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(),"UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }else{
                        throw new RequestException("参数不能为空 , " + entry.getKey() + " = " + entry.getValue() , 505);
                    }
                }
            }
            if(sb.length() > 0){
                return sb.substring(1);
            }else {
                return sb.toString();
            }
        }else{
            return "";
        }

    }

    protected String toUrl(){
        if(this.parameter != null && this.parameter.size() > 0){
            String parameter = this.toParameter();
            String flag = "?";
            if(this.path.contains("?")){
                flag = "&";
            }
            return this.baseUrl + this.path + flag + parameter;
        }else{
            return this.baseUrl + this.path;
        }
    }


    private void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
        if(!this.baseUrl.endsWith("/")){
            this.baseUrl = this.baseUrl + "/";
        }
    }

    private void setPath(String path) {
        this.path = path;
        if(this.path.startsWith("/")){
            this.path = this.path.substring(1);
        }
    }

    public static enum RequestType{
        PARAMETER,
        BODY
    }
}
